package com.sdry.web.controller.lz;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.mapper.llm.CancellingStockDetailMapper;
import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.ReceiveDetailQuality;
import com.sdry.model.llm.BarCode;
import com.sdry.model.lz.Car;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Contacts;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.LzQueryCriteria;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.OutStockOrder;
import com.sdry.model.lz.OutStockOrderDetail;
import com.sdry.model.lz.OutStockOrderDetailPDAEntity;
import com.sdry.model.lz.OutStockOrderPDAEntity;
import com.sdry.model.lz.Staff;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.lz.WarehouseRegion;
import com.sdry.model.tdd.emailRecord.EmailRecord;
import com.sdry.model.zc.ZcGeneralQueryEntity;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.model.zc.ZcTrayAndLocationEntity;
import com.sdry.service.barCodeOperation.BarCodeOperationService;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.jyy.UpService;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.llm.DeliveryNodeService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.service.tdd.emailRecord.EmailRecordService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.service.zc.ZcInventoryManagementService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.PushExample;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;

/**
 * @ClassName StockOutController
 * @Description 出库管理
 * @Author lz
 * @Date 2019年3月5日 13:58:34
 * @Version 1.0
 * 
 * 修改人：吉永艳
 * 修改时间：2019-11-05——2019-11-06
 * 修改内容：优化出库代码
 * 
 * 修改人：连雷明
 * 修改时间：2019-11-07
 * 修改方法：queryOutStockOrderCriteria 
 * 修改内容：310-315行，根据仓库ID，分页查询出库单
 * 修改方法：inventoryReductionOnlyCount 
 * 修改内容：2067-2070行， 根据仓库ID和物料，查库存
 * 修改方法：inventoryReductionOnlyCount 
 * 修改内容：1995-1997行， 添加参数，仓库ID
 */
@Controller
@RequestMapping("/stockOutOrder")
public class StockOutOrderController {
	public static final Integer AFFECT_ROW = 0;
	public static final String STOCKOUTORDER_TITLE = "出库单信息";

	@Resource
	StockOutOrderService stockOutService;

	@Resource
	ZcInventoryManagementService zcInventoryManagementService;
	
	@Resource
	CancellingStockDetailService cancellingStockDetailService;

	@Resource
	MaterielService materielService;
	
	@Resource
	CancellingStockDetailMapper cancellingStockDetailMapper;
	
	@Resource
	DeliveryNodeService deliveryNodeService;
	@Resource
	InventoryService inventoryService;
	
	@Resource
	BarCodeOperationService barCodeOperationService;
	
	@Resource
	ZcBindAndUnbindService zcBindAndUnbindService;
	
	@Resource
	ReceiveDetailService ReceiveDetailService;
	
	@Resource UpService upService;
	@Resource EmailRecordService emailRecordService;
	
	/**
	 * 新增出库单
	 * @param response
	 * @param order 出库单
	 */
	@RequestMapping("/addStockOutOrder")
	public void addStockOutOrder(HttpServletResponse response, OutStockOrder order){
		order.setStatus(0);
		Long affectRow = stockOutService.addStockOutOrder(order);
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新增出库单详细
	 * @param response
	 * @param outStockOrderDetail 出库单详细
	 * @throws Exception 
	 */
	@RequestMapping("/addStockOutOrderDetail")
	public void addStockOutOrderDetail(OutStockOrderDetail outStockOrderDetail,  HttpServletResponse response) {
		Long affact = stockOutService.addStockOutOrderDetail(outStockOrderDetail);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据ID删除出库单
	 * @param response
	 * @param idArr
	 */
	@RequestMapping("/deleteOutStockOrderById")
	public void deleteOutStockOrderById(HttpSession httpSession,HttpServletResponse response, @RequestParam("idArr[]") String[] idArr) throws Exception{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
       
        ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		
		if(idArr.length > 0){
			for (int i = 0; i < idArr.length; i++) {
				Map map = new HashMap();
				map.put("id",Long.parseLong(idArr[i]));
				map.put("cancellation_time", df.format(new Date()));
				map.put("cancellation", userName);
				Integer affact = stockOutService.cancelout(map);
				ResponseUtil.write(response, affact);
				map = null;
			}
		}
	}
	@RequestMapping("/restor")
	public void delet(HttpSession httpSession,HttpServletResponse response, @RequestParam("idArr[]") String[] idArr) throws Exception{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
	       
        ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		
		if(idArr.length > 0){
			for (int i = 0; i < idArr.length; i++) {
				Map map = new HashMap();
				map.put("id", Long.parseLong(idArr[i]));
				map.put("restorer_time", df.format(new Date()));
				map.put("restorer", userName);
				Integer affact = stockOutService.restorout(map);
				ResponseUtil.write(response, affact);
				map = null;
			}
		}
        
	}

	/**
	 * 根据出库单详细ID删除出库单详细
	 * @param response
	 * @param idArr 出库单详细ID
	 */
	@RequestMapping("/deleteOutStockOrderDetailById1")
	public void deleteOutStockOrderDetailById1(HttpServletResponse response, @RequestParam("idArr[]") String[] idArr){
		if(idArr.length > 0){
			for (int i = 0; i < idArr.length; i++) {
				Long affectRow = stockOutService.deleteOutStockOrderDetailById1(Long.parseLong(idArr[i]));
				if (affectRow > AFFECT_ROW) {
					try {
						ResponseUtil.write(response, affectRow);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					try {
						ResponseUtil.write(response, AFFECT_ROW);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 出库单的编辑
	 * @param response
	 * @param outStockOrder 出库单
	 */
	@RequestMapping("/updateStockOutOrder")
	public void updateStockOutOrder(HttpServletResponse response, OutStockOrder outStockOrder){
		Long affectRow = stockOutService.updateStockOutOrder(outStockOrder);
		if(affectRow > AFFECT_ROW){
			try {
				ResponseUtil.write(response, affectRow);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, "");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 行内编辑订单表详细
	 * @param response
	 * @param id 订单ID
	 * @param fieldName 修改的字段名称
	 * @param fieldValue 修改的字段的值
	 */
	@RequestMapping("/updateOutStockOrderDetailById")
	public void updateOutStockOrderDetailById(HttpServletResponse response, String id, String fieldName, String fieldValue){
		if(id != null) {
			Long affectRow = stockOutService.updateOutStockOrderDetailById(id, fieldName, fieldValue);
			if(affectRow > AFFECT_ROW) {
				try {
					ResponseUtil.write(response, affectRow);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				try {
					ResponseUtil.write(response, "");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 分页条件查询(出库单导入)
	 * @param response
	 * @param criteria
	 */
	@RequestMapping("/queryOutStockOrderCriteria")
	public void queryOutStockOrderCriteria(HttpServletResponse response, LzQueryCriteria criteria, HttpSession session){
		String keyword01 = criteria.getKeyword01();
		String keyword02 = criteria.getKeyword02();
		String keyword03 = criteria.getKeyword03();
		String keyword04 = criteria.getKeyword04();
		if(keyword01 == null){
			keyword01 = "";
		}
		if(keyword02 == null){
			keyword02 = "";
		}
        if(keyword03 == null){
            keyword03 = "";
        }
		if(keyword04 == null){
			keyword04 = "";
		}
		criteria.setKeyword01(keyword01);
		criteria.setKeyword02(keyword02);
		criteria.setKeyword03(keyword03);
		criteria.setKeyword04(keyword04);
		/******************** llm 修改 19.11.07 start ********************/
		Long warehouse_id = (Long)session.getAttribute("warehouse_id");
		if(warehouse_id != null){
			criteria.setKeyword05(warehouse_id.toString());
		}
		/******************** llm 修改 19.11.07 end **********************/
		List<OutStockOrder> outStockOrderList = stockOutService.queryOutStockOrderCriteria(criteria);
		int count = stockOutService.countOutStockOrderCriteria(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(outStockOrderList);
		jsonObject.put("code", AFFECT_ROW);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/queryOutStockOrderCriteria11")
	public void queryOutStockOrderCriteria11(HttpServletResponse response, LzQueryCriteria criteria){
		String keyword01 = criteria.getKeyword01();
		String keyword02 = criteria.getKeyword02();
		String keyword03 = criteria.getKeyword03();
		String keyword04 = criteria.getKeyword04();
		if(keyword01 == null){
			keyword01 = "";
		}
		if(keyword02 == null){
			keyword02 = "";
		}
        if(keyword03 == null){
            keyword03 = "";
        }
		if(keyword04 == null){
			keyword04 = "";
		}
		criteria.setKeyword01(keyword01);
		criteria.setKeyword02(keyword02);
		criteria.setKeyword03(keyword03);
		criteria.setKeyword04(keyword04);
		List<OutStockOrder> outStockOrderList = stockOutService.queryOutStockOrderCriteria11(criteria);
		int count = stockOutService.countOutStockOrderCriteria11(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(outStockOrderList);
		jsonObject.put("code", AFFECT_ROW);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 分页条件查询(装车处理)
	 * @param response
	 * @param criteria
	 */
	@RequestMapping("/queryOutStockOrderCriteria2")
	public void queryOutStockOrderCriteria2(HttpServletResponse response, LzQueryCriteria criteria){
		String keyword01 = criteria.getKeyword01();
		String keyword02 = criteria.getKeyword02();
		//String keyword03 = criteria.getKeyword03();
		if(keyword01 == null){
			keyword01 = "";
		}
		if(keyword02 == null){
			keyword02 = "";
		}
        /*if(keyword03 == null){
            keyword03 = "";
        }*/
		criteria.setKeyword01(keyword01);
		criteria.setKeyword02(keyword02);
		//criteria.setKeyword03(keyword03);
		List<OutStockOrder> outStockOrderList = stockOutService.queryOutStockOrderCriteria2(criteria);
		int count = stockOutService.countOutStockOrderCriteria2(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(outStockOrderList);
		jsonObject.put("code", AFFECT_ROW);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*________安卓接口(出库)start_________*/
	/**
	 * 查询所有的出库单
	 * @param response
	 */
	@RequestMapping("/queryOutStockOrderForPDA")
	public void queryOutStockOrderForPDA(String warehouse_id,HttpServletResponse response){
		List<OutStockOrderPDAEntity> outStockOrderList = stockOutService.queryOutStockOrderForPDA(warehouse_id);
		JSONObject jsonObject = new JSONObject();
		if(outStockOrderList.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", outStockOrderList);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 查询所有的出库单
	 * @param response
	 */
	@RequestMapping("/queryDeliveryOrderForPDA")
	public void queryDeliveryOrderForPDA(String warehouse_id,HttpServletResponse response){
		List<OutStockOrderPDAEntity> outStockOrderList = stockOutService.queryDeliveryOrderForPDA(warehouse_id);
		JSONObject jsonObject = new JSONObject();
		if(outStockOrderList.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", outStockOrderList);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 查询所有的紧急出库单
	 * @param response
	 */
	@RequestMapping("/queryUrgencyOrderForPDA")
	public void queryUrgencyOrderForPDA(String warehouse_id,HttpServletResponse response){
		List<OutStockOrderPDAEntity> outStockOrderList = stockOutService.queryUrgencyOrderForPDA(warehouse_id);
		JSONObject jsonObject = new JSONObject();
		if(outStockOrderList.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", outStockOrderList);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 查询所有出库单详细
	 * @param response
	 */
	@RequestMapping("/queryOutStockOrderDetailByIdForPDA")
	public void queryOutStockOrderDetailByIdForPDA(HttpServletResponse response, String out_stock_num_id){
		List<OutStockOrderDetailPDAEntity> outStockOrderDetailList = stockOutService.queryOutStockOrderDetailByIdForPDA(Long.parseLong(out_stock_num_id));
		JSONObject jsonObject = new JSONObject();
		if(outStockOrderDetailList.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", outStockOrderDetailList);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * app提交出库单的详细修改实际数量和出库状态
	 * @param json app提交的出库单详细实体
	 * 修改人：吉永艳
	 * 修改内容：将所有逻辑代码写到service层
	 * 修改时间：2019-11-05，2019-11-06
	 */
	@RequestMapping("/appSubmitOutStockOrderDetail")
	public void appSubmitOutStockOrderDetail(HttpServletResponse response, String person, String json, String warehouse_id){
		JSONObject jsonObject = new JSONObject();
		Long warehouseId = Long.valueOf(warehouse_id);
		Gson gson = new Gson();
		//json转list集合
		List<OutStockOrderDetailPDAEntity> outStockOrderDetailPDAEntityList = gson.fromJson(json, new TypeToken<List<OutStockOrderDetailPDAEntity>>() {}.getType());
		if(outStockOrderDetailPDAEntityList.size() > 0) {
			//--------------------------------------------jyy-start-------------------------------------------------------
			int result = stockOutService.appSubmitOutStockOrderDetail( person, warehouse_id, outStockOrderDetailPDAEntityList);
			//--------------------------------------------jyy-end-------------------------------------------------------
			if(result > 0) {
				jsonObject.put("status", "1");
				jsonObject.put("data", "出库成功");
			}else {
				jsonObject.put("status", "0");
				jsonObject.put("message", "出库失败");
			}
			
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "提交数据为空");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		afterOut(response,person,json,warehouseId);
	}
	
	/**
	 * 出库方法一分为2，这个是出库后的处理
	 * @author jyy
	 * 时间：2019-11-05
	 * @param response 响应
	 * @param person 操作人
	 * @param json 数据
	 */
	@RequestMapping("/afterOut")
	public void afterOut(HttpServletResponse response, String person, String json, Long warehouseId) {
		Gson gson = new Gson();
		CodeMark codeMark = new CodeMark();
		List<OutStockOrderDetailPDAEntity> outStockOrderDetailPDAEntityList = gson.fromJson(json, new TypeToken<List<OutStockOrderDetailPDAEntity>>() {}.getType());
		if(outStockOrderDetailPDAEntityList.size() > 0) {
			//----(1)给历史记录表插入数据start----
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = format.format(new Date());
			BarCodeOperation bar = new BarCodeOperation();
			for(OutStockOrderDetailPDAEntity detail : outStockOrderDetailPDAEntityList){
				bar.setOperator(Long.parseLong(person));
				bar.setMaterielId(detail.getMateriel().getId());
				bar.setOperatingTime(time);
				bar.setLocationId("缓存区");
				bar.setType("出库");
				bar.setResult("成功");
				bar.setWarehouse_id(warehouseId);
				for(CodeMark cm : detail.getReceiveCode()){
					bar.setBatch(cm.getPici());
					bar.setBarCode(cm.getCode());
					bar.setCodeNum(cm.getNum());
					bar.setCodeWeight(cm.getLinear_weight()+"");
					barCodeOperationService.insert(bar);
				}
			}
		}
	
		for (OutStockOrderDetailPDAEntity outStockOrderDetail : outStockOrderDetailPDAEntityList) {
			if ("".equals(outStockOrderDetail.getAct_num())) {
				outStockOrderDetail.setAct_num(0);
			}
			for (int j = 0; j < outStockOrderDetail.getReceiveCode().size(); j++) {
				if (outStockOrderDetail.getReceiveCode().get(j).getIs_ng() == 0) {
					
					//(2)根据APP传递过来的数据修改出库单详细的实际数量
					inventoryService.updateById(outStockOrderDetail.getId() + "", "actual_quantity", outStockOrderDetail.getAct_num() + "", "lz_out_stock_order_detail");
					inventoryService.updateById(outStockOrderDetail.getId() + "", "linear_weight", outStockOrderDetail.getLinear_weight() + "", "lz_out_stock_order_detail");
					/*=============(9).删除Codemark表的数据=============*/
					stockOutService.deleteCodemarkOutByCode(outStockOrderDetail.getReceiveCode().get(j).getCode());
					/*=============(10)给CodeMarkOut表添加数据=============*/
					codeMark = new CodeMark();
					codeMark.setReceive_detail_id(outStockOrderDetail.getId());
					codeMark.setCode(outStockOrderDetail.getReceiveCode().get(j).getCode());
					codeMark.setNum(outStockOrderDetail.getReceiveCode().get(j).getNum());
					codeMark.setWeight(outStockOrderDetail.getReceiveCode().get(j).getLinear_weight());
					stockOutService.addCodeMarkOut(codeMark);
					
					
					//==========良品库存预警==========
					Materiel materiel = materielService.queryMaterielById(outStockOrderDetail.getMateriel().getId());
					//(6)如果库存大于或小于预警值  报警
					StringBuffer buffer = new StringBuffer();
					Integer good = cancellingStockDetailMapper.getGoodQuantityInInventoryInfo(outStockOrderDetail.getMateriel().getId());
					if (materiel != null) {
						String materiel_num = materiel.getMateriel_num();
						String people = "";
						if (good >= materiel.getUpper_value()) {
							buffer.append(materiel_num);
							buffer.append("库存");
							buffer.append(good);
							buffer.append("大于等于");
							buffer.append(materiel.getUpper_value());
							buffer.append("特此报警");
							PushExample.testSendPush(buffer.toString() , "库存报警", people, "0");
						} else if (good <= materiel.getLower_value()) {
							buffer.append(materiel_num);
							buffer.append("库存");
							buffer.append(good);
							buffer.append("低于等于");
							buffer.append(materiel.getLower_value());
							buffer.append("特此报警");
							PushExample.testSendPush(buffer.toString() , "库存报警", people, "0");
						}
					}
					
					//==========end==========
					//(5)邮件推送
					//根据供应商id查询供应商的邮箱
					Customer customer = upService.queryCustomerEmailById(materiel.getCustomer_id());
					if (customer != null && !"".equals(buffer.toString())) {
						///////////////////////////添加邮件记录/////////////////////////////////
						EmailRecord emailRecord = new EmailRecord();
						emailRecord.setOperate("出库");
						emailRecord.setReceivePeopleId(customer.getId());
						emailRecord.setReceiveDate(DateUtil.dateFormat3());
						emailRecord.setEmailContent(buffer.toString());
						emailRecord.setRemark("0");
						emailRecord.setWarehouse_id(warehouseId);
						emailRecordService.insert(emailRecord);
					}
					//==========end==========
					buffer.setLength(0);
				} 
			}
		//(11)修改出库单状态
		stockOutService.updateOutStockOrderStatus(outStockOrderDetail);
		}
	}
	
	/**
	 * app提交出库单的详细修改实际数量和出库状态
	 * @param json app提交的出库单详细实体
	 */
	/*@RequestMapping("/appSubmitOutStockOrderDetail")
	public void appSubmitOutStockOrderDetail(HttpServletResponse response, String person, String json){
		String addStr = "";
		CodeMark codeMark;
		//json转list集合
		JSONObject jsonObject = new JSONObject();
		Gson gson = new Gson();
		List<OutStockOrderDetailPDAEntity> outStockOrderDetailPDAEntityList = gson.fromJson(json, new TypeToken<List<OutStockOrderDetailPDAEntity>>() {}.getType());
		if(outStockOrderDetailPDAEntityList.size() > 0) {
			//----(1)给历史记录表插入数据start----
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = format.format(new Date());
			BarCodeOperation bar = new BarCodeOperation();
			for(OutStockOrderDetailPDAEntity detail : outStockOrderDetailPDAEntityList){
				bar.setOperator(Long.parseLong(person));
				bar.setMaterielId(detail.getMateriel().getId());
				bar.setOperatingTime(time);
				bar.setType("出库");
				bar.setResult("成功");
				for(CodeMark cm : detail.getReceiveCode()){
					ReceiveDetailQuality byCode = inventoryService.queryReceiveByCode(cm.getCode());
					bar.setBatch(byCode.getPici());
					bar.setBarCode(cm.getCode());
					barCodeOperationService.insert(bar);
				}
			}
			//--------------end--------------
			for (OutStockOrderDetailPDAEntity outStockOrderDetail : outStockOrderDetailPDAEntityList) {
				if ("".equals(outStockOrderDetail.getAct_num())) {
					outStockOrderDetail.setAct_num(0);
				}
				//(2)根据APP传递过来的数据修改出库单详细的实际数量
				stockOutService.updateOutStockOrderDetailActNum(outStockOrderDetail.getId() + "",
						outStockOrderDetail.getAct_num() + "", outStockOrderDetail.getSingle_num() + "",
						outStockOrderDetail.getBig_num() + "", outStockOrderDetail.getSmall_num() + "");
				inventoryService.updateById(outStockOrderDetail.getId() + "", "actual_quantity", outStockOrderDetail.getAct_num() + "", "lz_out_stock_order_detail");
				//(3)减库存数量(遍历outStockOrderDetailPDAEntityList)
				for (int j = 0; j < outStockOrderDetail.getReceiveCode().size(); j++) {
					addStr = outStockOrderDetail.getReceiveCode().get(j).getCode() + ",";
					//根据收货单详情id查询相应的物料
					//Materiel materiel = stockOutService.queryMaterielByReceiveDetailId(outStockOrderDetailPDAEntityList.get(i).getReceiveCode().get(j).getReceive_detail_id());
					=============(4)根据质检单详情id查询质检单=============
					ReceiveDetailQuality receiveDetailQuality = stockOutService.queryReceiveDetailQualityById(outStockOrderDetail.getReceiveCode().get(j).getReceive_detail_id());
					=============(5)根据质检单中的物料id和批次首先减良品库存(物料id、物料批次、数量)=============
					if (outStockOrderDetail.getReceiveCode().get(j).getIs_ng() == 0) {
						stockOutService.reductionInventory(outStockOrderDetail.getMateriel().getId() + "",
								receiveDetailQuality.getPici(), outStockOrderDetail.getReceiveCode().get(j).getNum() + "");
						stockOutService.reductionInventoryCache(outStockOrderDetail.getMateriel().getId() + "",
								receiveDetailQuality.getPici(), outStockOrderDetail.getReceiveCode().get(j).getNum() + "");
						==========良品库存预警==========
						Materiel materiel = materielService.queryMaterielById(outStockOrderDetail.getMateriel().getId());
						//(6)如果库存大于或小于预警值  报警
						String content = "";
						Integer good = cancellingStockDetailMapper.getGoodQuantityInInventoryInfo(outStockOrderDetail.getMateriel().getId());
						if (materiel != null) {
							String materiel_num = materiel.getMateriel_num();
							String materiel_name = materiel.getMateriel_name();
							String people = "";
							if (good >= materiel.getUpper_value()) {
								content = materiel_num + "-" + materiel_name + "-" + "库存值大于最大预警值";
								PushExample.testSendPush(content , "库存报警", people, "0");
							} else if (good <= materiel.getLower_value()) {
								content = materiel_num + "-" + materiel_name + "-" + "库存值小于最小预警值";
								PushExample.testSendPush(content , "库存报警", people, "0");
							}
						}
						==========end==========
						==========(7)邮件推送==========
						try {
							//EmailUtils.sendQQMail("kyrieirving163@163.com", "库存报警", content);
						} catch (AddressException e) {
							e.printStackTrace();
						} catch (MessagingException e) {
							e.printStackTrace();
						}
						==========end==========
						
						
						//如果库存大于或小于预警值  报警
						String content = "";
						Integer good = cancellingStockDetailMapper.getGoodQuantityInInventoryInfo(outStockOrderDetail.getMateriel().getId());
						if (materiel != null) {
							String materiel_num = materiel.getMateriel_num();
							String materiel_name = materiel.getMateriel_name();
							String people = "";
							if (good >= materiel.getUpper_value()) {
								content = materiel_num + "-" + materiel_name + "-" + "库存值大于最大预警值";
								PushExample.testSendPush(content , "库存报警", people, "0");
							} else if (good <= materiel.getLower_value()) {
								content = materiel_num + "-" + materiel_name + "-" + "库存值小于最小预警值";
								PushExample.testSendPush(content , "库存报警", people, "0");
							}
							if (good >= materiel.getUpper_value()) {
								content = materiel_num + "库存" + good + "大于等于" + materiel.getUpper_value() + "特此报警";
								PushExample.testSendPush(content , "库存报警", people, "0");
							} else if (good <= materiel.getLower_value()) {
								content = materiel_num + "库存" + good + "低于等于" + materiel.getLower_value() + "特此报警";
								PushExample.testSendPush(content , "库存报警", people, "0");
							}
						}
						//==========end==========
						//(5)邮件推送
						//根据供应商id查询供应商的邮箱
						Customer customer = upService.queryCustomerEmailById(materiel.getCustomer_id());
						if (customer != null && !"".equals(content)) {
							try {
								EmailUtils.sendQQMail(customer.getCustomer_email(), "库存报警", content);
							} catch (Exception e) {
								e.printStackTrace();
							}
							///////////////////////////添加邮件记录/////////////////////////////////
							EmailRecord emailRecord = new EmailRecord();
							emailRecord.setOperate("出库");
							emailRecord.setReceivePeopleId(customer.getId());
							emailRecord.setReceiveDate(DateUtil.dateFormat3());
							emailRecord.setEmailContent(content);
							emailRecord.setRemark("0");
							emailRecordService.insert(emailRecord);
							////////////////////////////////////////////////////////////
						}
						//==========end==========
						
						
					} else {
						=============2.根据质检单中的物料id和批次再减不良品库存=============
						stockOutService.reductionRejectsWarehouse(outStockOrderDetail.getMateriel().getId() + "",
								receiveDetailQuality.getPici(), outStockOrderDetail.getReceiveCode().get(j).getNum() + "");
					}
					//(8)根据质检单中的物料id和批次减缓存库存
					Date date = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
					//String tray_code = System.currentTimeMillis() + "";
					//zcMaterielAndTrayEntity.setTray_code(tray_code);
					zcMaterielAndTrayEntity.setMateriel_code(addStr);
					zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(person));
					zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
					zcMaterielAndTrayEntity.setTargetRegion("");
					//zcMaterielAndTrayEntity.setLocation_code(location_code);
					int affact2 = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
					=============(9).删除Codemark表的数据=============
					stockOutService.deleteCodemarkOutByCode(outStockOrderDetail.getReceiveCode().get(j).getCode());
					=============(10)给CodeMarkOut表添加数据=============
					codeMark = new CodeMark();
					codeMark.setReceive_detail_id(outStockOrderDetail.getId());
					codeMark.setCode(outStockOrderDetail.getReceiveCode().get(j).getCode());
					codeMark.setNum(outStockOrderDetail.getReceiveCode().get(j).getNum());
					stockOutService.addCodeMarkOut(codeMark);
				}
				//(11)修改出库单状态
				stockOutService.updateOutStockOrderStatus(outStockOrderDetail);
			}
			jsonObject.put("status", "1");
			jsonObject.put("data", "出库成功");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
*/

	/**
	 * app提交出库单的详细修改实际数量和出库状态
	 * @param json app提交的出库单详细实体
	 * 修改人：吉永艳
	 * 修改时间：2019-11-06
	 * 修改内容：原来是循环每个条码的批次比较先进显出。现在与安卓一起修改，安卓比较判断每种物料下的每个条码，将最后的批次传给后台，后台只遍历比较每种物料的批次。减少遍历次数。提高校验效率
	 */
	@RequestMapping("/appSubmitOutStockOrderDetailJudge")
	public void appSubmitOutStockOrderDetailJudge(HttpServletResponse response, String person, String json, String warehouse_id){

		Integer temp = 0;
		//json转list集合
		JSONObject jsonObject = new JSONObject();
		Gson gson = new Gson();
		List<OutStockOrderDetailPDAEntity> outStockOrderDetailPDAEntityList = gson.fromJson(json, new TypeToken<List<OutStockOrderDetailPDAEntity>>() {}.getType());
		if(outStockOrderDetailPDAEntityList.size() > 0) {
			for(OutStockOrderDetailPDAEntity da : outStockOrderDetailPDAEntityList){
				/*for(CodeMark cm : da.getReceiveCode()){
					Boolean aBoolean = outStockOrderDetailJudge(cm.getCode());

					if (aBoolean == false) {
						jsonObject.put("status", "1");
						jsonObject.put("data", json);
						return;
					}
					if (aBoolean == false) {
						temp ++;
					}
				}*/
				//------------------------------------jyy-start--------------------------------------------------
				Boolean aBoolean = outStockOrderDetailJudge2(da.getMbatch(),da.getReceiveCode().get(0).getCode());
				//------------------------------------jyy-end--------------------------------------------------
				if (aBoolean == false) {
					temp ++;
				}
				
			}
		}
		if (temp > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("data", "6666666666");
		}else {
			appSubmitOutStockOrderDetail(response,person,json, warehouse_id);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 1.通过条码查找他们的（时间最早）批次号
	 * 2.缓存区批批号(zc_inventory_info_cache)
	 */
	/*public Boolean outStockOrderDetailJudge(String code) {
		//库存条码的时间
		String stockPiCi = inventoryService.getStockPiCi(code);
		//缓存区条码的时间
		String cachePiCi = inventoryService.getCachePiCi(code);
		if (StringUtil.isEmpty(stockPiCi)) {
			return false;
		}
		if (StringUtil.isEmpty(cachePiCi)) {
			return false;
		}
		//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			//Date date1 = format.parse(stockPiCi);
			//Date date2 = format.parse(cachePiCi);

			//long beginMillisecond = date1.getTime();
			//long endMillisecond = date2.getTime();

			long beginMillisecond = Long.parseLong(stockPiCi);
			long endMillisecond = Long.parseLong(cachePiCi);
			//System.out.println(beginMillisecond > endMillisecond);

			
			 //如果缓存区时间比较大，说明存储有之前还没有出库的
			 
			if (beginMillisecond > endMillisecond) {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}*/
	
	/**
	 * 1.通过条码查找他们的（时间最早）批次号
	 * 2.缓存区批批号(zc_inventory_info_cache)
	 * @author jyy
	 * 时间：2019-11-06
	 */
	public Boolean outStockOrderDetailJudge2(String pici,String code) {
		//库存条码的时间
		String stockPiCi = pici;
		//缓存区条码的时间
		String cachePiCi = inventoryService.getCachePiCi(code);
		if (StringUtil.isEmpty(stockPiCi) && StringUtil.isEmpty(cachePiCi)) {
			return false;
		}else {
			try {
				long beginMillisecond = Long.parseLong(stockPiCi);
				long endMillisecond = Long.parseLong(cachePiCi);

				 //如果缓存区时间比较大，说明存储有之前还没有出库的
				if (beginMillisecond > endMillisecond) {
					return false;
				}
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		return true;
	}

	/*
	 * 判断是否为整数
	 * @param str 传入的字符串
	 * @return 是整数返回true,否则返回false
	 */
	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}



	/**
	 * app提交紧急出库单的详细修改实际数量和出库状态
	 * @param json app提交的出库单详细实体
	 */
//	@RequestMapping("/appSubmitUrgencyOrderDetail")
//	public void appSubmitUrgencyOrderDetail(HttpServletResponse response, String person, String json){
//		String addStr = "";
//		CodeMark codeMark;
//		//json转list集合
//		JSONObject jsonObject = new JSONObject();
//		Gson gson = new Gson();
//		List<OutStockOrderDetailPDAEntity> outStockOrderDetailPDAEntityList = gson.fromJson(json, new TypeToken<List<OutStockOrderDetailPDAEntity>>() {}.getType());
//		if(outStockOrderDetailPDAEntityList.size() > 0) {
//			//--------------给历史记录表插入数据start--------------
//			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			String time = format.format(new Date());
//			BarCodeOperation bar = new BarCodeOperation();
//			for(OutStockOrderDetailPDAEntity detail : outStockOrderDetailPDAEntityList){
//				bar.setOperator(Long.parseLong(person));
//				bar.setMaterielId(detail.getMateriel().getId());
//				bar.setOperatingTime(time);
//				bar.setType("出库");
//				bar.setResult("成功");
//				for(CodeMark cm : detail.getReceiveCode()){
//					ReceiveDetailQuality byCode = inventoryService.queryReceiveByCode(cm.getCode());
//					bar.setBatch(byCode.getPici());
//					bar.setBarCode(cm.getCode());
//					barCodeOperationService.insert(bar);
//				}
//			}
//			//--------------end--------------
//			for (OutStockOrderDetailPDAEntity outStockOrderDetail : outStockOrderDetailPDAEntityList) {
//				if ("".equals(outStockOrderDetail.getAct_num())) {
//					outStockOrderDetail.setAct_num(0);
//				}
//				//1.根据APP传递过来的数据修改数量
////				stockOutService.updateOutStockOrderDetailActNum(outStockOrderDetail.getId() + "",
////						outStockOrderDetail.getAct_num() + "", outStockOrderDetail.getSingle_num() + "",
////						outStockOrderDetail.getBig_num() + "", outStockOrderDetail.getSmall_num() + "");
//				inventoryService.updateById(outStockOrderDetail.getId() + "", "actual_quantity", outStockOrderDetail.getAct_num() + "", "lz_out_stock_order_detail");
//				//2.减库存数量(遍历outStockOrderDetailPDAEntityList)
//				for (int j = 0; j < outStockOrderDetail.getReceiveCode().size(); j++) {
//					addStr += outStockOrderDetail.getReceiveCode().get(j).getCode() + ",";
//					//根据收货单详情id查询相应的物料
//					//Materiel materiel = stockOutService.queryMaterielByReceiveDetailId(outStockOrderDetailPDAEntityList.get(i).getReceiveCode().get(j).getReceive_detail_id());
//					/*=============1.根据质检单详情id查询质检单=============*/
//					ReceiveDetailQuality receiveDetailQuality = stockOutService.queryReceiveDetailQualityById(outStockOrderDetail.getReceiveCode().get(j).getReceive_detail_id());
//					/*=============2.根据质检单中的物料id和批次首先减良品库存=============*/
//					if (outStockOrderDetail.getReceiveCode().get(j).getIs_ng() == 0) {
//						stockOutService.reductionInventory(outStockOrderDetail.getMateriel().getId() + "",
//								receiveDetailQuality.getPici(), outStockOrderDetail.getReceiveCode().get(j).getNum() + "");
//						/*stockOutService.reductionInventoryCache(outStockOrderDetail.getMateriel().getId() + "",
//								receiveDetailQuality.getPici(), outStockOrderDetail.getReceiveCode().get(j).getNum() + "");*/
//						/*==========良品库存预警==========*/
//						Materiel materiel = materielService.queryMaterielById(outStockOrderDetail.getMateriel().getId());
//						//如果库存大于或小于预警值  报警
//						/*String content = "";
//						Integer good = cancellingStockDetailMapper.getGoodQuantityInInventoryInfo(outStockOrderDetail.getMateriel().getId());
//						if (materiel != null) {
//							String materiel_num = materiel.getMateriel_num();
//							String materiel_name = materiel.getMateriel_name();
//							String people = "";
//							if (good > materiel.getUpper_value()) {
//								content = materiel_num + "-" + materiel_name + "-" + "库存值大于最大预警值";
//								PushExample.testSendPush(content , "库存报警", people, "0");
//							} else if (good < materiel.getLower_value()) {
//								content = materiel_num + "-" + materiel_name + "-" + "库存值小于最小预警值";
//								PushExample.testSendPush(content , "库存报警", people, "0");
//							}
//						}*/
//						/*==========end==========*/
//						/*==========邮件推送==========*/
//						/*try {
//							//EmailUtils.sendQQMail("kyrieirving163@163.com", "库存报警", content);
//						} catch (AddressException e) {
//							e.printStackTrace();
//						} catch (MessagingException e) {
//							e.printStackTrace();
//						}*/
//						/*==========end==========*/
//					} else {
//						/*=============2.根据质检单中的物料id和批次再减不良品库存=============*/
//						stockOutService.reductionRejectsWarehouse(outStockOrderDetail.getMateriel().getId() + "",
//								receiveDetailQuality.getPici(), outStockOrderDetail.getReceiveCode().get(j).getNum() + "");
//					}
//					/*=============4.给CodeMarkOut表添加数据=============*/
//					codeMark = new CodeMark();
//					codeMark.setReceive_detail_id(outStockOrderDetail.getId());
//					codeMark.setCode(outStockOrderDetail.getReceiveCode().get(j).getCode());
//					codeMark.setNum(outStockOrderDetail.getReceiveCode().get(j).getNum());
//					//根据质检单中的物料id和批次减缓存库存
//					/*************************减质检区数量（不同出库单）*************************/
//					Date date = new Date();
//					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
//					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
//					//String tray_code = System.currentTimeMillis()+"";
//					//zcMaterielAndTrayEntity.setTray_code(tray_code);
//					zcMaterielAndTrayEntity.setMateriel_code(addStr);
//					zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(person));
//					zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
//					zcMaterielAndTrayEntity.setTargetRegion("DJ");
//					//zcMaterielAndTrayEntity.setLocation_code(location_code);
//					int affact2 = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
//					zcMaterielAndTrayEntity.setTargetRegion("");
//					int affact3 = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
//					/*=============3.删除Codemark表的数据=============*/
//					stockOutService.deleteCodemarkOutByCode(outStockOrderDetail.getReceiveCode().get(j).getCode());
//					stockOutService.addCodeMarkOut(codeMark);
//					/*************************减质检区数量（不同出库单）*************************/
//				}
//				//5.修改出库单状态
//				stockOutService.updateOutStockOrderStatus(outStockOrderDetail);
//			}
//			jsonObject.put("status", "1");
//			jsonObject.put("data", "出库成功");
//		} else {
//			jsonObject.put("status", "0");
//			jsonObject.put("message", "查询数据为空");
//		}
//		
//		try {
//			ResponseUtil.write(response, jsonObject);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	
	
	@RequestMapping("/appSubmitUrgencyOrderDetail")
	public void appSubmitUrgencyOrderDetail(HttpServletResponse response, String person, String json, String warehouse_id){
		
		Long warehouseId = Long.valueOf(warehouse_id);
		
		String addStr = "";
		CodeMark codeMark;
		//json转list集合
		JSONObject jsonObject = new JSONObject();
		Gson gson = new Gson();
		List<OutStockOrderDetailPDAEntity> outStockOrderDetailPDAEntityList = gson.fromJson(json, new TypeToken<List<OutStockOrderDetailPDAEntity>>() {}.getType());
		if(outStockOrderDetailPDAEntityList.size() > 0) {
			//--------------给历史记录表插入数据start--------------
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = format.format(new Date());
			BarCodeOperation bar = new BarCodeOperation();
			for(OutStockOrderDetailPDAEntity detail : outStockOrderDetailPDAEntityList){
				bar.setOperator(Long.parseLong(person));
				bar.setMaterielId(detail.getMateriel().getId());
				bar.setOperatingTime(time);
				bar.setType("出库");
				bar.setResult("成功");
				bar.setWarehouse_id(Long.valueOf(warehouse_id));
				for(CodeMark cm : detail.getReceiveCode()){
					ReceiveDetailQuality byCode = inventoryService.queryReceiveByCode(cm.getCode());
					bar.setBatch(byCode.getPici());
					bar.setBarCode(cm.getCode());
					bar.setCodeNum(cm.getNum());
					barCodeOperationService.insert(bar);
				}
			}
			//--------------end--------------
			for (OutStockOrderDetailPDAEntity outStockOrderDetail : outStockOrderDetailPDAEntityList) {
				if ("".equals(outStockOrderDetail.getAct_num())) {
					outStockOrderDetail.setAct_num(0);
				}
				//1.根据APP传递过来的数据修改数量
				inventoryService.updateById(outStockOrderDetail.getId() + "", "actual_quantity", outStockOrderDetail.getAct_num() + "", "lz_out_stock_order_detail");
				//2.减库存数量(遍历outStockOrderDetailPDAEntityList)
				for (int j = 0; j < outStockOrderDetail.getReceiveCode().size(); j++) {
					addStr += outStockOrderDetail.getReceiveCode().get(j).getCode() + ",";
					//根据收货单详情id查询相应的物料
					/*=============1.根据质检单详情id查询质检单=============*/
					ReceiveDetailQuality receiveDetailQuality = stockOutService.queryReceiveDetailQualityById(outStockOrderDetail.getReceiveCode().get(j).getReceive_detail_id());
					/*=============2.根据质检单中的物料id和批次首先减良品库存=============*/
					if (outStockOrderDetail.getReceiveCode().get(j).getIs_ng() == 0) {
						stockOutService.reductionInventory(outStockOrderDetail.getMateriel().getId() + "",
								receiveDetailQuality.getPici(), outStockOrderDetail.getReceiveCode().get(j).getNum() + "", warehouseId);
						/*==========良品库存预警==========*/
						Materiel materiel = materielService.queryMaterielById(outStockOrderDetail.getMateriel().getId());
						//如果库存大于或小于预警值  报警
						/*==========end==========*/
					} else {
						/*=============2.根据质检单中的物料id和批次再减不良品库存=============*/
						stockOutService.reductionRejectsWarehouse(outStockOrderDetail.getMateriel().getId() + "",
								receiveDetailQuality.getPici(), outStockOrderDetail.getReceiveCode().get(j).getNum() + "");
					}
					/*=============4.给CodeMarkOut表添加数据=============*/
					codeMark = new CodeMark();
					codeMark.setReceive_detail_id(outStockOrderDetail.getId());
					codeMark.setCode(outStockOrderDetail.getReceiveCode().get(j).getCode());
					codeMark.setNum(outStockOrderDetail.getReceiveCode().get(j).getNum());
					//根据质检单中的物料id和批次减缓存库存
					/*************************减质检区数量（不同出库单）*************************/
					updateUnCheckQuantity(outStockOrderDetail.getReceiveCode().get(j).getCode());
					/*=============3.删除Codemark表的数据=============*/
					stockOutService.deleteCodemarkOutByCode(outStockOrderDetail.getReceiveCode().get(j).getCode());
					stockOutService.addCodeMarkOut(codeMark);
					/*************************减质检区数量（不同出库单）*************************/
				}
				//5.修改出库单状态
				stockOutService.updateOutStockOrderStatus(outStockOrderDetail);
			}
			jsonObject.put("status", "1");
			jsonObject.put("data", "出库成功");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
		}
		
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * app提交出库单的详细修改实际数量和出库状态
	 * @param json app提交的出库单详细实体
	 */
	@RequestMapping("/appSubmitDeliveryOrderDetail")
	public void appSubmitDeliveryOrderDetail(HttpServletResponse response, String json, HttpSession session){
		//json转list集合
		JSONObject jsonObject = new JSONObject();
		Gson gson = new Gson();
		List<OutStockOrderDetailPDAEntity> outStockOrderDetailPDAEntityList = gson.fromJson(json, new TypeToken<List<OutStockOrderDetailPDAEntity>>() {}.getType());
		if(outStockOrderDetailPDAEntityList.size() > 0) {
			for(OutStockOrderDetailPDAEntity detail : outStockOrderDetailPDAEntityList){
				if ("".equals(detail.getAct_num())) {
					detail.setAct_num(0);
				}
				//1.根据APP传递过来的数据修改数量
				deliveryNodeService.updateById4(detail.getId().toString(), "actual_quantity", detail.getAct_num()+"", "lz_out_stock_order_detail");
				//deliveryNodeService.updateInventoryByMid(detail.getMateriel().getId().toString(), "mNum", detail.getAct_num()+"", "zc_inventory_info_only_count");
				inventoryReductionOnlyCount(detail.getMateriel().getId(), detail.getAct_num(), session);
			}
			//5.修改出库单状态
			stockOutService.updateOutStockOrderStatus(outStockOrderDetailPDAEntityList.get(0));
			jsonObject.put("status", "1");
			jsonObject.put("data", "出库成功");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "提交数据为空");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 精简出库web页面确认出库
	 * @param id 出库单id
	 */
	@RequestMapping("/webSubmitDeliveryOrderDetail")
	public void webSubmitDeliveryOrderDetailWeb(HttpServletResponse response, Long id, HttpSession session){
		//json转list集合
		JSONObject jsonObject = new JSONObject();
		//根据出库单id查出库单
		//List<OutStockOrder> outStockOrderList = stockOutService.queryOutStockOrderStatusByOutStockNumId(id);
		OutStockOrderDetailPDAEntity updateOutStockOrderStatus = new OutStockOrderDetailPDAEntity();
		updateOutStockOrderStatus.setOut_stock_num_id(id);
		//根据出库单id查详情
		List<OutStockOrderDetailPDAEntity> outStockOrderDetailList = stockOutService.queryOutStockOrderDetailByIdForPDA(id);
		
		if(outStockOrderDetailList.size() > 0) {
			for(OutStockOrderDetailPDAEntity detail : outStockOrderDetailList){
				if ("".equals(detail.getPre_num())) {
					detail.setPre_num(0);
				}
				//1.根据APP传递过来的数据修改数量
				deliveryNodeService.updateById4(detail.getId().toString(), "actual_quantity", detail.getPre_num()+"", "lz_out_stock_order_detail");
				//deliveryNodeService.updateInventoryByMid(detail.getMateriel().getId().toString(), "mNum", detail.getAct_num()+"", "zc_inventory_info_only_count");
				inventoryReductionOnlyCount(detail.getMateriel().getId(), detail.getPre_num(), session);
			}
			//5.修改出库单状态
			stockOutService.updateOutStockOrderStatus(updateOutStockOrderStatus);
			jsonObject.put("status", "1");
			jsonObject.put("data", "出库成功");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "该出库单物料为空");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*________安卓接口(出库)end_________*/
	
	/**
	 * 根据订单编号查询订单详细
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryOutStockOrderCriteriaById")
	public void queryOutStockOrderCriteriaById(HttpServletResponse response, LzQueryCriteria criteria) {
		String keyword01 = criteria.getKeyword01();
		String keyword02 = criteria.getKeyword02();
		if(keyword01 == null){
			keyword01 = "";
		}
		if(keyword02 == null){
			keyword02 = "";
		}
		criteria.setKeyword01(keyword01);
		criteria.setKeyword02(keyword02);
		List<OutStockOrderDetail> outStockOrderList = stockOutService.queryOutStockOrderCriteriaById(criteria);
		int count = stockOutService.countOutStockOrderCriteriaById(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(outStockOrderList);
		jsonObject.put("code", AFFECT_ROW);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 根据订单编号查询订单详细2
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryOutStockOrderCriteriaById2")
	public void queryOutStockOrderCriteriaById2(HttpServletResponse response, LzQueryCriteria criteria) {
		String keyword01 = criteria.getKeyword01();
		String keyword02 = criteria.getKeyword02();
		if(keyword01 == null){
			keyword01 = "";
		}
		if(keyword02 == null){
			keyword02 = "";
		}
		criteria.setKeyword01(keyword01);
		criteria.setKeyword02(keyword02);
		List<OutStockOrderDetail> outStockOrderList = stockOutService.queryOutStockOrderCriteriaById2(criteria);
		int count = stockOutService.countOutStockOrderCriteriaById(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(outStockOrderList);
		jsonObject.put("code", AFFECT_ROW);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 根据订单编号查询订单详细3
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryOutStockOrderCriteriaById3")
	public void queryOutStockOrderCriteriaById3(HttpServletResponse response, LzQueryCriteria criteria) {
		String keyword01 = criteria.getKeyword01();
		String keyword02 = criteria.getKeyword02();
		if(keyword01 == null){
			keyword01 = "";
		}
		if(keyword02 == null){
			keyword02 = "";
		}
		criteria.setKeyword01(keyword01);
		criteria.setKeyword02(keyword02);
		List<OutStockOrderDetail> outStockOrderList = stockOutService.queryOutStockOrderCriteriaById3(criteria);
		int count = stockOutService.countOutStockOrderCriteriaById(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(outStockOrderList);
		jsonObject.put("code", AFFECT_ROW);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<String> titleListTemplateMachineList(){
		List<String> list = new ArrayList<>();
		list.add("出库单号");
		list.add("业务单号");
		list.add("出库类型");
		list.add("出库模式");
		list.add("状态");
		list.add("客户");
		list.add("收货方");
		list.add("要求出库数量");
		list.add("实际出库数量");
		list.add("要求出库日期");
		list.add("创建人");
		list.add("创建时间");
		return list;
	}

	@RequestMapping("/exportFileMachineList")
	public void ExportFileMachineList(HttpServletResponse response) {
		try {
			downLoadOutOrderTemplet(STOCKOUTORDER_TITLE, titleListTemplateMachineList(), response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *
	 * @param title
	 * @param list
	 * @param response
	 * @throws Exception
	 */
	public static void downLoadOutOrderTemplet(String title, List<String> list, HttpServletResponse response) {
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet(title);
		sheet.setColumnWidth(0, 256 * 20 + 184);
		sheet.setColumnWidth(1, 256 * 20 + 184);
		sheet.setColumnWidth(2, 256 * 20 + 184);
		sheet.setColumnWidth(3, 256 * 20 + 184);
		sheet.setColumnWidth(4, 256 * 20 + 184);
		sheet.setColumnWidth(5, 256 * 20 + 184);
		sheet.setColumnWidth(6, 256 * 20 + 184);
		sheet.setColumnWidth(7, 256 * 20 + 184);
		sheet.setColumnWidth(8, 256 * 20 + 184);
		sheet.setColumnWidth(9, 256 * 20 + 184);
		sheet.setColumnWidth(10, 256 * 20 + 184);
		sheet.setColumnWidth(11, 256 * 20 + 184);
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow((int) 0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 创建一个居中格式
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		HSSFFont headerFont = (HSSFFont) wb.createFont();
		//headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		headerFont.setFontName("微软雅黑");
		headerFont.setFontHeightInPoints((short)11);
		style.setFont(headerFont);
		style.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		HSSFCell cell;
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				cell = row.createCell(i);
				cell.setCellValue(list.get(i));
				cell.setCellStyle(style);
			}
		}
		list = null;
		// 第六步，将文件存到指定位置
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//可以方便地修改日期格式
		String nowtime = dateFormat.format(now);

		String fileName = title + nowtime +".xls";
		try {
			fileName = new String(fileName.getBytes("GBK"),"iso8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			response.reset();
			response.setHeader("Content-Disposition","attachment;filename="+fileName);//指定下载的文件名
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查找所有客户
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryAllCustomer")
	public void queryAllCustomer(HttpServletResponse response) {
		List<Customer> customerList = stockOutService.queryAllCustomer();
		JSONArray jsonArray = JSONArray.fromObject(customerList);
		if (customerList.size() > 0) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 查找所有供应商
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryAllCustomerByType")
	public void queryAllCustomerByType(HttpServletResponse response) {
		List<Customer> customerList = stockOutService.queryAllCustomerByType();
		JSONArray jsonArray = JSONArray.fromObject(customerList);
		if (customerList.size() > 0) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 查找所有库区
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryAllRegion")
	public void queryAllRegion(HttpServletResponse response) {
		List<WarehouseRegion> warehouseRegionList = stockOutService.queryAllRegion();
		JSONArray jsonArray = JSONArray.fromObject(warehouseRegionList);
		if (warehouseRegionList.size() > 0) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 查找所有人员
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryAllStaff")
	public void queryAllStaff(HttpServletResponse response) {
		List<Staff> staffList = stockOutService.queryAllStaff();
		JSONArray jsonArray = JSONArray.fromObject(staffList);
		if (staffList.size() > 0) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 查找所有车辆
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryAllCar")
	public void queryAllCar(HttpServletResponse response) {
		List<Car> carList = stockOutService.queryAllCar();
		JSONArray jsonArray = JSONArray.fromObject(carList);
		if (carList.size() > 0) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping("/queryDriver")
	public void queryDriver(HttpServletResponse response,String id) {
		Car car = stockOutService.queryDriver(Long.parseLong(id));
		JSONArray jsonArray = JSONArray.fromObject(car);
		try {
			ResponseUtil.write(response, jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询未完成的出库单
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryAllOutStockOrder")
	public void queryAllOutStockOrder(HttpServletResponse response) {
		List<OutStockOrder> outStockOrderList = stockOutService.queryAllOutStockOrder();
		JSONArray jsonArray = JSONArray.fromObject(outStockOrderList);
		if (outStockOrderList.size() > 0) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 根据客户名称查询客户地址
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryCustomerByName")
	public void queryCustomerByName(HttpServletResponse response, String customer_name) {
		List<Customer> customerList = stockOutService.queryCustomerByName(customer_name);
		JSONArray jsonArray = JSONArray.fromObject(customerList.get(0));
		if (customerList.size() > 0) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 出库减数量
	 * @param materiel_id 物料id
	 * @param res3 仓库库存的最终值
	 */
 	@RequestMapping("/updateZcInventoryInfoById")
	public void updateZcInventoryInfoById(String materiel_id, String res3){
		Long materielId = Long.parseLong(materiel_id);
		Integer materielQuantity = Integer.parseInt(res3);
		//根据物料ID查良品库的库存
		List<ZcInventoryInfoEntity> list = cancellingStockDetailService.getInventoryByMid(materielId);
		//遍历减库存（1个物料ID多条库存记录，减后为0的，删除该记录）
		for(ZcInventoryInfoEntity info : list){
			System.out.println("物料ID="+materielQuantity+":  库存数量="+info.getmNum());
			materielQuantity = materielQuantity - info.getmNum();
			//如果物料数量大于库存
			if(materielQuantity > 0){
				//删除这条数据
				cancellingStockDetailService.deleteInventoryById(info.getId());
			}else{
				//修改库存数量
				Map<String, Object> map = new HashMap<>();
				map.put("id", info.getId());
				map.put("fieldName", "mNum");
				map.put("fieldValue", Math.abs(materielQuantity));
				cancellingStockDetailService.updateInventory(map);
				break;
			}
		}
	}
	/*ZcInventoryInfoEntity zcInventoryInfoEntity = stockOutService.triggerWarning(zcInventoryInfoId);
	if(zcInventoryInfoEntity.getFloor() > Integer.parseInt(finalFieldValue)) {
		PushExample.testSendPush("出库时库存不足！","库存不足","1","2");
	}
	Long affectRow = stockOutService.updateZcInventoryInfoById(materiel_id,  res3);
	if(affectRow > AFFECT_ROW){
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	} else {
		try {
			ResponseUtil.write(response, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/

	/**
	 * 查询未出库的出库单(Android)
	 * @param response
	 */
 	@RequestMapping("/queryOutStockOrderAndroid")
	public void queryOutStockOrderAndroid(HttpServletResponse response) {
		List<OutStockOrder> outStockOrderList = stockOutService.queryOutStockOrderAndroid();
		JSONObject jsonObject = new JSONObject();
		if(outStockOrderList.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", outStockOrderList);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 根据出库单id查询详细(Android)
	 * @param response
	 */
	@RequestMapping("/queryOutStockOrderDetailByIdAndroid")
	public void queryOutStockOrderDetailByIdAndroid(HttpServletResponse response, String order_id) {
		List<OutStockOrderDetail> outStockOrderDetailList = stockOutService.queryOutStockOrderDetailByIdAndroid(order_id);
		JSONObject jsonObject = new JSONObject();
		if(outStockOrderDetailList.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", outStockOrderDetailList);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 修改出库单状态(Android)
	 * @param response
	 * @param json 接收安卓参数
	 * @throws Exception
	 */
	@RequestMapping("/updateStockOutOrderDetailStatusAndroid")
	public void updateStockOutOrderDetailStatusAndroid(HttpServletResponse response, String json) {
		Gson gson = new Gson();
		List<BarCode> barCodeList = gson.fromJson(json, new TypeToken<List<BarCode>>() {}.getType());
		JSONObject jsonObject = new JSONObject();
		if(barCodeList.size() > AFFECT_ROW) {
			for (int i = 0; i < barCodeList.size(); i++) {
				Long affectRow = stockOutService.updateStockOutOrderDetailStatusAndroid(barCodeList.get(i));
				if(affectRow > AFFECT_ROW){
					try {
						jsonObject.put("status", "1");
						jsonObject.put("data", "提交成功");
						ResponseUtil.write(response, jsonObject);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					try {
						jsonObject.put("status", "0");
						jsonObject.put("message", "提交失败");
						ResponseUtil.write(response, jsonObject);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			System.out.println("盘点单详细为空");
		}
	}

	/**根据仓库id查询仓库
	 * @param response
	 * @param id 仓库id
	 * @throws Exception
	 */
	@RequestMapping("/queryWarehouseById")
	public void queryWarehouseById(HttpServletResponse response, String id) {
		Warehouse warehouse = stockOutService.queryWarehouseById(Long.parseLong(id));
		JSONArray jsonArray = JSONArray.fromObject(warehouse);
		if (warehouse != null) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**根据用户id查询用户
	 * @param response
	 * @param id 用户id
	 * @throws Exception
	 */
	@RequestMapping("/queryUserById")
	public void queryUserById(HttpServletResponse response, String id) {
		ZcSysUserEntity user = stockOutService.queryUserById(Long.parseLong(id));
		JSONArray jsonArray = JSONArray.fromObject(user);
		if (user != null) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**根据用户id查询用户
	 * @param response
	 * @param id 用户id
	 * @throws Exception
	 */
	@RequestMapping("/queryCustomerById")
	public void queryCustomerById(HttpServletResponse response, String id) {
		Customer customer = stockOutService.queryCustomerById(Long.parseLong(id));
		JSONArray jsonArray = JSONArray.fromObject(customer);
		if (customer != null) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**根据用户id查询用户
	 * @param response
	 * @param id 用户id
	 * @throws Exception
	 */
	@RequestMapping("/queryContactsById")
	public void queryContactsById(HttpServletResponse response, String id) {
		Contacts contacts = stockOutService.queryContactsById(Long.parseLong(id));
		JSONArray jsonArray = JSONArray.fromObject(contacts);
		if (contacts != null) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 出库时先查询待发货区
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryWaitSendAreaAndStock")
	public void queryWaitSendAreaAndStock(HttpServletResponse response, LzQueryCriteria criteria) {
		List<Materiel> materielList = stockOutService.queryWaitSendAreaAndStock(criteria);
		int count = stockOutService.countWaitSendAreaAndStock(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(materielList);
		jsonObject.put("code", AFFECT_ROW);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 分页查询库存表
	 * @param response
	 * @param criteria
	 */
	@RequestMapping("/queryInventoryInfo")
	public void queryInventoryInfo(HttpServletResponse response, LzQueryCriteria criteria){
		List<ZcInventoryInfoEntity> zcInventoryInfoList = stockOutService.queryInventoryInfo(criteria);
		int count = stockOutService.countInventoryInfo(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(zcInventoryInfoList);
		jsonObject.put("code", AFFECT_ROW);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询库存信息
	 * @param response
	 * @param zcGeneralQueryEntity
	 */
	@RequestMapping("selectInventoryInfoList")
	public void selectInventoryInfoList(HttpServletResponse response, ZcGeneralQueryEntity zcGeneralQueryEntity){
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		List<ZcInventoryInfoEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoList(zcGeneralQueryEntity);
		int count = zcInventoryManagementService.countInventoryInfoList(zcGeneralQueryEntity);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(inventoryInfoList, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 减库存表
	 * @param materielId
	 * @param materielQuantity
	 */
	@RequestMapping("/inventoryReductionURL")
	public void inventoryReductionURL(HttpServletResponse response, Long materielId, Integer materielQuantity) {
		inventoryReduction(materielId, materielQuantity);
		try {
			ResponseUtil.write(response, 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 减物料良品库的库存
	 * @param materielId 物料ID
	 * @param materielQuantity	物料数量
	 */
	public void inventoryReduction(Long materielId, Integer materielQuantity) {
		//根据物料ID查良品库的库存
		List<ZcInventoryInfoEntity> list = cancellingStockDetailService.getInventoryByMid(materielId);
		//遍历减库存（1个物料ID多条库存记录，减后为0的，删除该记录）
		/*for(ZcInventoryInfoEntity info : list){*/
		for(int i = 0; i < list.size(); i++) {
			//System.out.println("补发数量="+materielQuantity+":  库存数量="+info.getmNum());
			materielQuantity = materielQuantity - list.get(i).getSmallNum();
			//如果物料数量大于库存
			if(materielQuantity > 0){
				//删除这条数据
				//cancellingStockDetailService.deleteInventoryById(info.getId());
				int materielQuantity1;
				materielQuantity1= list.get(i).getBigNum() - materielQuantity ;
				if(materielQuantity1 > 0) {
					//修改库存数量
					Map<String, Object> map = new HashMap<>();
					map.put("id", list.get(i).getId());
					map.put("fieldName", "mNum");
					map.put("fieldValue", Math.abs(materielQuantity1));
					cancellingStockDetailService.updateInventory(map);
					Map<String, Object> map1 = new HashMap<>();
					map1.put("id", list.get(i).getId());
					map1.put("fieldName", "bigNum");
					map1.put("fieldValue", Math.abs(materielQuantity1));
					cancellingStockDetailService.updateInventory(map1);
					Map<String, Object> map2 = new HashMap<>();
					map2.put("id", list.get(i).getId());
					map2.put("fieldName", "smallNum");
					map2.put("fieldValue", 0);
					cancellingStockDetailService.updateInventory(map2);
					break;
				} else {
					//删除这条数据
					cancellingStockDetailService.deleteInventoryById(list.get(i).getId());
					//求绝对值
					inventoryReduction(list.get(i).getMid(), Math.abs(materielQuantity1));
				}
			} else {
				//修改库存数量
				Map<String, Object> map = new HashMap<>();
				map.put("id", list.get(i).getId());
				map.put("fieldName", "smallNum");
				map.put("fieldValue", Math.abs(materielQuantity));
				cancellingStockDetailService.updateInventory(map);
				Map<String, Object> map1 = new HashMap<>();
				map1.put("id", list.get(i).getId());
				map1.put("fieldName", "mNum");
				map1.put("fieldValue", Math.abs(materielQuantity)+list.get(i).getBigNum());
				cancellingStockDetailService.updateInventory(map1);
			}
			break;
		}
	}
	
	/**
	 * 查询所有主机厂
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryAllCustomerByType1")
	public void queryAllCustomerByType1(HttpServletResponse response, HttpSession session) {
		/********************* llm 19.11.08 修改 start  ******************/
		Long warehouseId = (Long)session.getAttribute("warehouse_id");
		List<Customer> customerList = stockOutService.queryAllCustomerByType1(warehouseId);
		/********************* llm 19.11.08 修改  end   ******************/
//		List<Customer> customerList = stockOutService.queryAllCustomerByType1();
		JSONArray jsonArray = JSONArray.fromObject(customerList);
		if (customerList.size() > 0) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 查询该出库单详细是否存在该物料
	 * @param response
	 * @param outStockOrderDetail 出库单详细
	 * @throws Exception
	 */
	@RequestMapping("/queryExistMaterial")
	public void queryExistMaterial(HttpServletResponse response, OutStockOrderDetail outStockOrderDetail) {
		List<OutStockOrderDetail> outStockOrderDetailList = stockOutService.queryExistMaterial(outStockOrderDetail);
		if (outStockOrderDetailList.size() > 0) {
			try {
				ResponseUtil.write(response, 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, 0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 根据出库单id查询出库单状态
	 * @param response
	 * @param out_stock_num_id 出库单id
	 * @throws Exception
	 */
	@RequestMapping("/queryOutStockOrderStatusByOutStockNumId")
	public void queryOutStockOrderStatusByOutStockNumId(HttpServletResponse response, String out_stock_num_id) {
		List<OutStockOrder> outStockOrderList = stockOutService.queryOutStockOrderStatusByOutStockNumId(Long.parseLong(out_stock_num_id));
		//如果为1就是已出库
		if (outStockOrderList.get(0).getStatus() > 0) {
			try {
				ResponseUtil.write(response, 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, 0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 减物料良品库的库存(精简出库)
	 * @param materielId 物料ID
	 * @param materielQuantity	物料数量
	 */
	public void inventoryReductionOnlyCount(Long materielId, Integer materielQuantity, HttpSession session) {
		/******************* llm 19.11.07 修改  start **************************/
		Long warehouse_id = (Long)session.getAttribute("warehouse_id");
		List<ZcInventoryInfoEntity> list = cancellingStockDetailService.getInventoryOnlyCountByMid(materielId, warehouse_id);
		/******************* llm 19.11.07 修改  end   **************************/
		//根据物料ID查良品库的库存
//		List<ZcInventoryInfoEntity> list = cancellingStockDetailService.getInventoryOnlyCountByMid(materielId);
		//遍历减库存（1个物料ID多条库存记录，减后为0的，删除该记录）
		for(ZcInventoryInfoEntity info : list){
			materielQuantity = materielQuantity - info.getmNum();
			//如果物料数量大于库存
			if(materielQuantity >= 0){
				//删除这条数据
				cancellingStockDetailService.deleteInventoryOnlyCountById(info.getId());
			}else{
				//修改库存数量
				Map<String, Object> map = new HashMap<>();
				map.put("id", info.getId());
				map.put("fieldName", "mNum");
				map.put("fieldValue", Math.abs(materielQuantity));
				cancellingStockDetailService.updateInventoryOnlyCount(map);
				break;
			}
		}
	}
	
	/**
	 * 紧急出库接口(APP)
	 * @param code 条码
	 * @param
	 */
	@RequestMapping("/queryQualityMaterielOut")
	public void queryQualityMaterielOut(String code, String warehouse_id, HttpServletResponse response) {
		Long warehouseId = Long.valueOf(warehouse_id);
		boolean flag = true;
		String codeArr = "";
		codeArr += code + ",";
		String location_code = zcBindAndUnbindService.selectByMaterielCode(codeArr, warehouseId);
		JSONObject jsonObject = new JSONObject();
		//判断待检区是否存在该条码
		if ("DJ".equals(location_code)) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", flag);
		}else {
			flag = false;
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "不能出库");
		    jsonObject.put("data", flag);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据条码减待检区库存
	 * @param co
	 */
	public void updateUnCheckQuantity(String co){
		//1、找到条码对应的托盘
		String code = "," + co +",";
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(code);
		CodeMark cm = cancellingStockDetailService.queryCodeByCode(co);
		if(zcMaterielAndTrayEntity != null){
			//2、用“”替换托盘中的条码
			String mCode = zcMaterielAndTrayEntity.getMateriel_code();
			String newCode2 = mCode.replace(co +",", "");
			inventoryService.updateById(zcMaterielAndTrayEntity.getId()+"", "mNum", (zcMaterielAndTrayEntity.getmNum() - cm.getNum()) + "", "zc_materiel_tray");
			//3、判断托盘中的条码是否为空
			if(newCode2.length() == 0){
				//3.1、如果托盘空了，则删除这条数据
				ReceiveDetailService.deleteMaterielTrayById(zcMaterielAndTrayEntity.getId());
				//根据托盘码查询托盘物料信息
				List<ZcMaterielAndTrayEntity> zcMaterielAndTrayEntity1 = ReceiveDetailService.selectZcMaterielAndTrayEntityByTray(zcMaterielAndTrayEntity.getTray_code());
				if (null == zcMaterielAndTrayEntity1 || zcMaterielAndTrayEntity1.size() == 0){
					//3.1.2、在库位和托盘的绑定表中用“”替换原托盘码
					String tray = zcMaterielAndTrayEntity.getTray_code() + ",";
					ZcTrayAndLocationEntity zcTrayAndLocationEntity = ReceiveDetailService.queryTrayLocationByTray(tray);
					if(zcTrayAndLocationEntity != null){
						String trays = zcTrayAndLocationEntity.getTray_code();
						String newTrays = trays.replace(tray, "");
						//3.1.3如果替换后字段为空，删除字段，否则修改
						if(newTrays.length() == 0){
							ReceiveDetailService.deleteTrayLocationById(zcTrayAndLocationEntity.getId());
						}else{
							inventoryService.updateById(zcTrayAndLocationEntity.getId()+"", "tray_code", newTrays, "zc_tray_location");
						}
					}
				}
			}else{
				//3.2、把替换后的条码集合放回原来托盘
				ReceiveDetailService.updateMaterielTrayByCode(zcMaterielAndTrayEntity.getId() + "", newCode2);
			}
			//4、在待检区的库存表中减数量
			Map<String, Object> map = new HashMap<>();
			map.put("mid", zcMaterielAndTrayEntity.getMid());
			map.put("mBatch", zcMaterielAndTrayEntity.getmBatch());
			map.put("num", cm.getNum());
			ReceiveDetailService.updateQuantityByMidAndPici(map);
		}
	}
	/**
     * 导出Excel
     * @param response
	 * @throws UnsupportedEncodingException 
     * @throws Exception
     */
    @RequestMapping("/doExportall")
    public void doExportall(HttpServletResponse response,HttpSession session, LzQueryCriteria criteria) throws UnsupportedEncodingException{
		String keyword01 = criteria.getKeyword01();
		String keyword04 = criteria.getKeyword04();
		String keyword03 = criteria.getKeyword03();
		String keyword02 = criteria.getKeyword02();
		if(keyword01 == null){
			keyword01 = "";
		}
		if(keyword04 == null){
			keyword04 = "";
		}
        if(keyword03 == null){
            keyword03 = "";
        }
		criteria.setKeyword01(keyword01);
		criteria.setKeyword02(keyword02);
		criteria.setKeyword03(keyword03);
		criteria.setKeyword04(keyword04);
		criteria.setPage(1);
 		criteria.setLimit(10000);
 		/******************** llm 修改 19.11.07 start ********************/
		Long warehouse_id = (Long)session.getAttribute("warehouse_id");
		if(warehouse_id != null){
			criteria.setKeyword05(warehouse_id.toString());
		}
		/******************** llm 修改 19.11.07 end **********************/
		List<OutStockOrder> outStockOrderList = stockOutService.queryOutStockOrderCriteria(criteria);
		//List<OutStockOrderDetail> outStockOrderdetailList = stockOutService.queryOutStockOrderCriteriaById(criteria);
		LzQueryCriteria criteria1=new LzQueryCriteria();
        List<List<String>> lists = zhuanlist(outStockOrderList,criteria1);
        ExcelUtils.export("出库所有数据",namess(), response, lists);
    }

    public List<String> namess() {
        List<String> list = new ArrayList<>();
        list.add("序号");
        list.add("出库单号");
        list.add("创建时间");
        list.add("仓库名称");
        
        list.add("仓库地址");
        list.add("目的地名称");
        list.add("目的地地址");
        list.add("目的地负责人");
        list.add("负责人电话");
        list.add("状态");
        list.add("客户单号");
        list.add("是否取消");
        list.add("取消人");
        
        list.add("取消时间");
      
        list.add("恢复人");
        
        list.add("恢复时间");
        list.add("备注");
      
        return list;
    }

    public List<List<String>> zhuanlist (List<OutStockOrder> outStockOrderList, LzQueryCriteria criteria) throws UnsupportedEncodingException{
		
		{
        List<List<String>> lists = new ArrayList<>();
           for (OutStockOrder stockOrder : outStockOrderList) {
		    List<String> list = new ArrayList<>();
             list.add(String.valueOf(stockOrder.getId()));
             list.add(stockOrder.getOut_stock_num());
             list.add(stockOrder.getCreate_date());
             list.add(stockOrder.getWarehouse_name());
           
             list.add(stockOrder.getWarehouse_address());
             list.add(stockOrder.getCustomer_name());
             list.add(stockOrder.getCustomer_address());
             list.add(stockOrder.getContacts_name());
             list.add(stockOrder.getContacts_tel());
             
             
             if(stockOrder.getStatus()==0) {
            	 
             list.add("未出库");
             }else if(stockOrder.getStatus()==1) {
            	 list.add("已出库");
             }else if(stockOrder.getStatus()==2) {
            	 list.add("配送中");
             }
             else if(stockOrder.getStatus()==3) {
            	 list.add("已到达");
             }
             else if(stockOrder.getStatus()==4) {
            	 list.add("已收货");
             }
             list.add(stockOrder.getCustomer_order());
             
             if(stockOrder.getFlag().equals("0")) {
            	 
             list.add("已取消");
             }else if(stockOrder.getFlag().equals("1")) {
            	 
             list.add("已恢复");
             }else {
                	 list.add("未操作");
            }
             list.add(stockOrder.getCancellation());
             list.add(stockOrder.getCancellation_time());
             list.add(stockOrder.getRestorer());
             list.add(stockOrder.getRestorer_time());
             list.add(stockOrder.getRemark());
             lists.add(list);
             List<String> listd = new ArrayList<>();
             listd.add("出库单编号为"+stockOrder.getOut_stock_num()+"的出库单详情表");
             lists.add(listd);
             List<String> listn = new ArrayList<>();
            listn.add("供应商名称");
            listn.add("SAP/QAD");
             listn.add("中文名称");
             listn.add("零件号");
             listn.add("可出库数");
             listn.add("缓存区数");
             listn.add("出库数量");
             listn.add("实际出库");
             
             lists.add(listn);
            criteria.setKeyword01(String.valueOf(stockOrder.getId()));
     		criteria.setKeyword02("");
     		criteria.setPage(1);
     		criteria.setLimit(10000);
             List<OutStockOrderDetail> outStockOrderdetailList = stockOutService.queryOutStockOrderCriteriaById(criteria);
            for (OutStockOrderDetail detail : outStockOrderdetailList) {
            	 List<String> list1 = new ArrayList<>();
            	 list1.add(detail.getCustomer_name());
              
            	 list1.add(detail.getMateriel_num());
                 list1.add(detail.getMateriel_name());
                 list1.add(detail.getBrevity_num());
                 
                 list1.add(String.valueOf(detail.getSmall_num()));
                 list1.add(String.valueOf(detail.getSingle_num()));
                 list1.add(String.valueOf(detail.getMaterial_quantity()));
                 list1.add(String.valueOf(detail.getActual_quantity()));
                 lists.add(list1);
                 list1 = null;
			}
            list = null;
        }
        return lists;
    }
}
    
}
